import cgi
import datetime
import time
import urlparse
import wsgiref.handlers

from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

def getOpmServer(index):
    opmServers = []
    opmServers.append('http://rogerxu-opm.appspot.com/')
    opmServers.append('http://server4.operamini.com/')
    opmServers.append('http://demo.opera-mini.net:9002/')
    opmServers.append('http://google-cust.opera-mini.net/')
    opmServers.append('http://global-4-lvs-usa.opera-mini.net/')
    opmServers.append('http://p09-15.opera-mini.net/')
    opmServers.append('http://r01-15.opera-mini.net/')
    opmServers.append('http://r03-15.opera-mini.net/')

    return opmServers[index]

class PingPage(webapp.RequestHandler):

    def get(self):
        if (self.request.get('index')):
            index = int(self.request.get('index'))
            url = getOpmServer(index)
        else:
            domain = self.request.get('domain', default_value='server4.operamini.com')
            url = 'http://%s/' % (domain)

        t1 = time.time()
        headers = {'Content-Type': 'application/xml'}
        urlfetch.fetch(url=url, method=urlfetch.GET, headers=headers, deadline=5)
        t2 = time.time()
        delay = (t2 - t1) * 1000.0

        self.response.set_status(200)
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write('This is Opera Mini Server Proxy!<br />\n')
        self.response.out.write('Current Server: %s => %d ms' % (url, delay))

application = webapp.WSGIApplication([
    ('/ping', PingPage)
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
